<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="接口名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入接口名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="interfaceList" border @selection-change="handleSelectionChange">

      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="Header">
              <span>{{ props.row.header }}</span>
            </el-form-item>
            <el-form-item label="返回内容">
              <span style="width: 30%">{{ props.row.responseContent }}</span>
            </el-form-item>
            <el-form-item label="备注">
              <span>{{ props.row.remark }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="接口名称" align="left" width="200" prop="name"/>
      <el-table-column label="URL" :show-overflow-tooltip="true" width="200" align="left" prop="url"/>
      <el-table-column label="接口类型" align="center" prop="type">
        <template slot-scope="scope">
          <el-tag :type="scope.row.type === 1 ? 'success' : 'primary'" disable-transitions>
            <dict-tag :options="dict.type.stock_interface_type" :value="scope.row.type"/>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="请求参数" align="center" :show-overflow-tooltip="true" prop="parameter"/>
      <el-table-column label="请求Body" align="center" :show-overflow-tooltip="true" prop="body"/>
      <el-table-column label="请求缓存" align="center" prop="cookie"/>
      <el-table-column label="接口访问时间" align="center" prop="accessTime" width="160"></el-table-column>
      <el-table-column label="状态" width="60" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_common_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleTest(scope.row)">测试</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改接口对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="接口名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入接口名称"/>
        </el-form-item>
        <el-form-item label="接口URL" prop="url">
          <el-input v-model="form.url" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="接口类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择接口类型">
            <el-option v-for="dict in dict.type.stock_interface_type" :key="dict.value" :label="dict.label"
                       :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请求参数" prop="parameter">
          <el-input v-model="form.parameter" type="textarea" placeholder="请输入内容"/>
        </el-form-item>

        <el-form-item label="Header">
          <el-table :data="headerData" border style="width: 100%">
            <el-table-column label="参数名" align="center" prop="date">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.name"
                  placeholder="参数名"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="参数值" align="center" prop="date">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.value"
                  placeholder="参数值"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" width="120">
              <template slot="header" slot-scope="scope">
                <el-button type="danger" plain icon="el-icon-plus" size="mini" @click="handleAddRow(scope.$index, headerData)"></el-button>
              </template>
              <template slot-scope="scope">
                <el-button type="danger" plain icon="el-icon-plus" size="mini" @click="handleAddRow(scope.$index, headerData)"></el-button>
                <el-button type="danger" plain icon="el-icon-minus" size="mini"
                           @click="handleRemoveRow(scope.$index, headerData)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="请求缓存" prop="cookie">
          <el-input v-model="form.cookie" placeholder="请输入请求缓存"/>
        </el-form-item>
        <el-form-item label="返回内容">
          <el-input v-model="form.responseContent" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 展示Json组件-->
    <json-show ref="jsonShowRef" :visible.sync="jsonShowVisible" :jsonData="jsonData"/>

  </div>
</template>

<script>
import { addInterface, delInterface, getInterface, listInterface, testInterface, updateInterface } from '@/api/eye/interface'
import JsonShow from '../components/JsonShow'
import {getNowTime} from '@/utils/dateUtil'

export default {
  name: 'Interface',
  // 注册组件
  components: {
    JsonShow
  },
  dicts: ['stock_interface_type', 'sys_common_status'],
  data() {
    return {
      headerData: [],
      // 测试结果弹出层
      jsonShowVisible: false,
      // 测试结果
      jsonData: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 接口表格数据
      interfaceList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        url: null,
        type: null,
        parameter: null,
        cookie: null,
        body: null,
        header: null,
        responseContent: null,
        accessTime: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: '接口名称不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '接口类型不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询接口列表 */
    getList() {
      this.loading = true
      listInterface(this.queryParams).then(response => {
        this.interfaceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        url: null,
        type: 1,
        parameter: null,
        cookie: null,
        body: null,
        header: null,
        responseContent: null,
        accessTime: null,
        status: 0,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.form.type = 1
      this.open = true
      this.title = '添加接口'
    },
    /* 点击测试 */
    handleTest(row) {
      console.log('点击测试')
      this.loading = true
      testInterface(row).then(response => {
        this.loading = false
        this.jsonShowVisible = true
        if (response.msg === 'OK') {
          row.status = 0
          this.jsonData = response
        } else {
          row.status = 1
          this.jsonData = response
        }
        row.accessTime = getNowTime()
        listInterface(this.queryParams).then(response => {
          this.interfaceList = response.rows
          this.total = response.total
        })
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.headerData = []
      const id = row.id || this.ids
      getInterface(id).then(response => {
        this.form = response.data
        if (response.data.header != null && response.data.header.length > 0) {
          // 字符串header转换成数组
          this.headerData = JSON.parse(response.data.header)
        }
        this.open = true
        this.title = '修改接口'
      })
    },
    /** 提交按钮 */
    submitForm() {
      console.log('提交')
      console.log(this.headerData)
      if (this.headerData.length > 0) {
        this.form.header = JSON.stringify(this.headerData)
      }else {
        this.form.header = ""
      }
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInterface(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addInterface(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除接口编号为"' + ids + '"的数据项？').then(function() {
        return delInterface(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 添加行 */
    handleAddRow(index, data) {
      console.log('添加行')
      console.log(index)
      data.splice(index + 1, 0, {})
      console.log(data)
    },
    /** 移除行 */
    handleRemoveRow(index, data) {
      console.log('移除行')
      console.log(index)
      data.splice(index, 1)
      console.log(data)
      console.log(this.headerData)
    }
  }
}
</script>


<style>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 100%;
}

.demo-table-expand .el-form-item .el-form-item__label{
  width: 6%;
}

/*换行，背景色*/
.demo-table-expand .el-form-item .el-form-item__content{
  background-color: #33292908;
  width: 94%;
  word-wrap: break-word;
}
</style>
